package com.tang.repository.impl;

import com.tang.entity.Book;
import com.tang.entity.BookCase;
import com.tang.entity.Borrow;
import com.tang.repository.BookRepository;
import com.tang.service.impl.BookServiceImpl;
import com.tang.utils.JDBCTools;

import javax.sound.midi.SoundbankResource;
import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tang
 * @create 2020-08-17
 */
public class BookRepositoryImpl implements com.tang.repository.BookRepository {

    @Override
    public int findAll() {
        int pages = 0;
        Connection connection = JDBCTools.getConnection();
        String sql = "SELECT count(*) from book,bookcase WHERE book.bookcaseid = bookcase.id ORDER BY book.id";
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();

            while (resultSet.next()){
                  pages = resultSet.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCTools.release(connection,statement,resultSet);
            return pages;
        }


    }

    @Override
    public List<Book> find(int index, int limit) {
        List<Book> list = new ArrayList<>();
        Connection connection = JDBCTools.getConnection();
        String sql = "SELECT * from book,bookcase WHERE book.bookcaseid = bookcase.id ORDER BY book.id limit ?,?";
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            statement = connection.prepareStatement(sql);
            statement.setInt(1, index);
            statement.setInt(2, limit);
            resultSet = statement.executeQuery();

            while (resultSet.next()) {
                list.add(new Book(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), resultSet.getString(4),
                        resultSet.getInt(5), resultSet.getInt(6), new BookCase(resultSet.getInt(9), resultSet.getString(10))));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection,statement,resultSet);
            return list;
        }

    }

}
